﻿#include "LicenseCodeManagement.h"

//构造函数：判读文件
LicenseCodeManagement::LicenseCodeManagement()
{
    //判断文件是否存在
    m_FilePath = "LicenseKey.dat";
    QFile file(m_FilePath);
    if(file.exists()){
        //文件存在，执行解密操作
        if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
            m_ResultCode = FILE_READ_FAILED;
            return;
        }
        QTextStream in(&file);
        //授权码验证
        licenseValidate(in.readLine(),0);
    }
    else{ //文件不存在
        m_ResultCode =  FILE_NOT_EXIST;
    }
}

//获取结果码
ResultCode LicenseCodeManagement::getResultCode()
{
    return m_ResultCode;
}

//获取机型id
QString LicenseCodeManagement::getPlaneTypeID()
{
    return m_PlaneTypeIDStr;
}

//获取机器码
QString LicenseCodeManagement::getMachineCode()
{
    QString cpuCode,hardDiskcode,macCode;
    cpuCode = getHardwareSerialNumber("wmic cpu get processorid");
    hardDiskcode = getHardwareSerialNumber("wmic diskdrive get serialnumber");
    macCode = getMacAddress();

    QString md5Key = encryptionMD5(cpuCode+"-"+hardDiskcode+"-"+macCode);
    return md5Key;
}

//获取机器序列号
QString LicenseCodeManagement::getHardwareSerialNumber(const QString &cmd)
{
    QProcess p;
    p.start(cmd);
    p.waitForFinished();

    QString result=QString::fromLocal8Bit(p.readAllStandardOutput());
    QStringList list=cmd.split(" ");
    result=result.remove(list.last(),Qt::CaseInsensitive);
    result=result.replace("\r","");
    result=result.replace("\n","");
    result=result.replace("-", "");
    result=result.simplified();
    p.kill();
    p.close();

    return result;
}

//获取MAC地址
QString LicenseCodeManagement::getMacAddress()
{
    QList<QNetworkInterface> nets=QNetworkInterface::allInterfaces();
    int nCnt=nets.count();
    QString strMacAddr="";
    for(int i=0;i<nCnt;i++)
    {
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp)&& nets[i].flags().testFlag(QNetworkInterface::IsRunning)&& !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr=nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}

///
/// \brief LicenseCodeManagement::licenseValidate
/// \param licenseStr 授权码
/// \param creatFileFlag 创建dat文件标志
///授权码验证
void LicenseCodeManagement::licenseValidate(QString licenseStr, bool creatFileFlag)
{
    //AES解密
    m_DecryptionContextStr = decryptionAES(licenseStr,AES_KEY);

    //截取获得需要比较的机器码和日期范围
    QStringList licenseDateList = m_DecryptionContextStr.split("-"); //去掉分隔符，组成QStringList
    m_MachineCode = licenseDateList[0];
    m_EndDate = QDate::fromString(licenseDateList[licenseDateList.count()-1]);
    m_StartDate = QDate::fromString(licenseDateList[licenseDateList.count()-2]);
    for(int i=0; i< licenseDateList.count(); i++){
        qDebug()<<licenseDateList[i]<<endl;
    }

    //进行机器码判断
    if(getMachineCode() == m_MachineCode){ //如果该机器码被授权，则进行授权日期判断
        if(!((m_CurrentDate>m_StartDate || m_CurrentDate==m_StartDate) && (m_CurrentDate<m_EndDate || m_CurrentDate == m_EndDate))){
            m_ResultCode= LICENSE_DATE_ERROR;    //如果系统日期不在授权日期范围内，反馈授权日期错误
        }
        else{  //如果授权日期正确，则获取授权机型id
            for(int i=0; i<licenseDateList.count();i++){
                if(!((i==0)||(i==licenseDateList.count()-1)||(i==licenseDateList.count()-2))){ //去除机器码，开始日期和结束日期，获得授权的机型id
                    m_PlaneTypeIDList.append(licenseDateList[i]);
                }
            }
            m_PlaneTypeIDStr = m_PlaneTypeIDList.join("-"); //添加分隔符，组成QString

            //写入文件
            if(creatFileFlag){ //创建文件标志为true
                QFile file(m_FilePath);
                if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
                    return;
                }
                file.write(licenseStr.toUtf8());
                file.close();
            }
            m_ResultCode = SUCCESS;
        }
    }
    else{
        m_ResultCode= NO_LICENSE; //该设备未被授权
    }
}

//MD5加密
QString LicenseCodeManagement::encryptionMD5(const QString &data)
{
    QCryptographicHash md5(QCryptographicHash::Md5); //使用MD5加密
    md5.addData(data.toUtf8(),data.size()); //添加数据
    QByteArray bArry=md5.result(); //获取MD5后加密的密码
    QString md5_date;
    md5_date.append(bArry.toHex());
    return md5_date;
}

//AES解密
QString LicenseCodeManagement::decryptionAES(QString data, QString key)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
    QByteArray decodedText = encryption.decode(QByteArray::fromBase64(data.toLatin1()), hashKey);
    QString decodedTextStr = QString::fromLatin1(decodedText);

    return decodedTextStr;
}
